package xyz.bali16.module.blog.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import xyz.bali16.module.blog.utils.PageUtils;
import xyz.bali16.module.blog.entity.Article;
import xyz.bali16.module.blog.mapper.ArticleMapper;
import xyz.bali16.module.blog.mapper.CategoryMapper;
import xyz.bali16.module.blog.mapper.TagMapper;
import xyz.bali16.module.blog.model.vo.blog.ArticleConditionVo;
import xyz.bali16.module.blog.service.ArticleService;
import xyz.bali16.module.netdisk.utils.CoreConst;

import java.util.List;


@Service("ArticleService")
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private TagMapper tagMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public PageUtils queryPage(Integer curPage, Integer pageSize) {
        IPage<Article> page = this.page(new Page<>(curPage,pageSize));
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(ArticleConditionVo vo) {
        return new PageUtils(vo.getCurrent(),vo.getSize(),findByCondition(vo),queryCount());
    }

    @Override
    public List<Article> findByCondition(ArticleConditionVo vo) {
        List<Article> list = articleMapper.findByCondition(vo);
//        if (CollectionUtils.isNotEmpty(list)) {
//            for (Article article : list) {
                /**laod tag to article**/
//				List<Tag> tagList = tagMapper.selectByArticleId(article.getId());
//				article.setTags(tagList);
                /**load category to article**/
//				Category category = categoryMapper.selectByArticleId(article.getId());
//				article.setCategory(category);
//            }
//        }
        return list;
    }

    @Override
    public List<Article> findByCondition(IPage<Article> page, ArticleConditionVo vo) {
        List<Article> list = articleMapper.findPageByCondition(page, vo);
//        if (CollectionUtils.isNotEmpty(list)) {
//            for (Article article : list) {
//                /**laod tag to article**/
////				List<Tag> tagList = tagMapper.selectByArticleId(article.getId());
////				article.setTags(tagList);
//                /**load category to article**/
////				Category category = categoryMapper.selectByArticleId(article.getId());
////				article.setCategory(category);
//            }
//        }
        return list;
    }

//	@Override
//	public PageUtils queryArticlePage(Integer curPage, Integer pageSize, ArticleConditionVo vo) {
//		List<Question> articles = findByCondition(vo);
//		return new PageUtils(curPage,pageSize,articles);
//	}



    @Override
    public List<Article> findByArticleUrl(String articleUrl) {
        return this.list(Wrappers.<Article>lambdaQuery().eq(Article::getUrl, articleUrl));
    }

//
//	@Override
//	public List<Article> recentList(Integer pageSize) {
//		ArticleConditionVo vo = new ArticleConditionVo();
//		vo.setSize(pageSize);
//		vo.setStatus(CoreConst.Status.AVAILABLE);
//		vo.setRecentFlag(true);
//		IPage<Article> page = new Pagination<>(vo.getPageNumber(), vo.getPageSize());
//		return this.findByCondition(page, vo);
//	}

	@Override
	public List<Article> randomList(Integer pageSize) {
        ArticleConditionVo vo = new ArticleConditionVo();
        vo.setSize(pageSize);
        vo.setStatus(0);
        vo.setRandom(true);
        return findByCondition(vo);
	}

	@Override
	public List<Article> hotList(Integer pageSize) {
        ArticleConditionVo vo = new ArticleConditionVo();
        vo.setSize(pageSize);
        vo.setStatus(0);
        vo.setSortOrder("desc");
        vo.setSortName("views");
        return findByCondition(vo);
	}

    //	@Override
//	public Integer countByStatus(Integer status, String post) {
//
//	}

    @Override
    public Integer findRepeatByUrl(String articleUrl) {
        return null;
    }


    /**
     * 设置文章状态  0 已发布 1 草稿 2 回收站
     **/
    @Override
    public boolean updateStatus(Long id, Integer statusId) {
        Article article = getById(id);
        article.setStatus(statusId);
        return updateById(article);
    }


    @Override
    public Integer queryCount() {
        return articleMapper.queryCount();
    }
//
//
//	/**
//	 * 自动生成的mapper里配置了useGeneratedKeys="true" keyProperty="id" 如重新生成请复制过去
//	 */
//	@Override
//	@CacheEvict(value = ARTICLES_CACHE_NAME, allEntries = true, beforeInvocation = true)
//	public void save(Question article, Long[] tags, Long[] categorys) throws Exception {
//		articleMapper.insert(article);
//		if (categorys != null) {
//			Arrays.asList(categorys).stream().forEach(cate -> {
//				QuestionCategory articleCategory = new QuestionCategory();
//				articleCategory.setArticleId(article.getId());
//				articleCategory.setCategoryId(cate);
//				articleCategoryMapper.insert(articleCategory);
//			});
//		}
//		if (tags != null) {
//			Arrays.asList(tags).stream().forEach(tag -> {
//				ArticleTagMapper articleTag = new ArticleTagMapper();
//				articleTag.setArticleId(article.getId());
//				articleTag.setTagId(tag);
//				articleTagMapper.insert(articleTag);
//			});
//		}
//	}
//
//	@Override
//	@Cacheable(value = ARTICLES_CACHE_NAME, key = "'findAllArticle'+#status+#post")
//	public List<Question> findAllArticle(int status, String post) {
//		return articleMapperCustom.findAllArticle(status,post);
//	}
//
//	@Override
//	@Cacheable(value = ARTICLES_CACHE_NAME, key = "'findPageArticle'+#page+#limit+#Question.articleStatus+#Question.articlePost")
//	public PageInfo<Question> findPageArticle(int page, int limit, Question Question) {
//		PageHelper.startPage(page, limit);
//		List<Question> lists = articleMapperCustom.findPageArticle(Question);
//		return new PageInfo<>(lists);
//	}
//
//	@Override
//	@Cacheable(value = ARTICLES_CACHE_NAME, key = "'Post_status'+#status+#post")
//	public Integer countByStatus(Integer status, String post) {
//		return articleMapperCustom.countByStatus(status, post);
//	}
//
//	@Override
//	@CacheEvict(value = ARTICLES_CACHE_NAME, allEntries = true, beforeInvocation = true)
//	public void recycle(int id, Integer integer) throws Exception {
//		articleMapperCustom.updateStatus(id, integer);
//	}
//
//	@Override
//	@CacheEvict(value = ARTICLES_CACHE_NAME, allEntries = true, beforeInvocation = true)
//	public void remove(int id) throws Exception {
//		// 删除文章表
//		articleMapper.deleteByPrimaryKey(id);
//		ArticleTagExample articleTagexample = new ArticleTagExample();
//		ArticleTagExample.Criteria tagCriteria = articleTagexample.createCriteria();
//		tagCriteria.andArticleIdEqualTo(id);
//		ArticleCategoryExample articleCategoryExample = new ArticleCategoryExample();
//		ArticleCategoryExample.Criteria categoryCriteria = articleCategoryExample.createCriteria();
//		categoryCriteria.andArticleIdEqualTo(id);
//		// 删除分类表和标签表
//		articleTagMapper.deleteByExample(articleTagexample);
//		articleCategoryMapper.deleteByExample(articleCategoryExample);
//	}
//
//	@Override
//	@Cacheable(value = ARTICLES_CACHE_NAME, key = "'findByArticleId'+#article_id")
//	public Question findByArticleId(Integer article_id) {
//		return articleMapperCustom.findByArticleId(article_id);
//	}
//
//	@Override
//	@CacheEvict(value = ARTICLES_CACHE_NAME, allEntries = true, beforeInvocation = true)
//	public void update(Question article, Long[] tags, Long[] categorys) throws Exception {
//		// 修改文章
//		articleMapper.updateByPrimaryKeySelective(article);
//		// 先查出关联的分类与标签
//		List<Integer> tagList = tagMapperCustom.selectByarticleId(article.getId());
//		List<Integer> cateList = categoryMapperCustom.selectByarticleId(article.getId());
//		if (tagList != null && tagList.size() > 0) {
//			// 然后删除
//			tagMapperCustom.delete(tagList, article.getId());
//		}
//		if (cateList != null && cateList.size() > 0) {
//			categoryMapperCustom.delete(cateList, article.getId());
//		}
//		// 再添加
//		// 鬼知道我最开始为什么这样子设计。。。等到都写完了就不愿意改了，先用着吧
//		if (categorys != null) {
//			Arrays.asList(categorys).stream().forEach(cate -> {
//				QuestionCategory articleCategory = new QuestionCategory();
//				articleCategory.setArticleId(article.getId());
//				articleCategory.setCategoryId(cate);
//				articleCategoryMapper.insert(articleCategory);
//			});
//		}
//		if (tags != null) {
//			Arrays.asList(tags).stream().forEach(tag -> {
//				ArticleTagMapper articleTag = new ArticleTagMapper();
//				articleTag.setArticleId(article.getId());
//				articleTag.setTagId(tag);
//				articleTagMapper.insert(articleTag);
//			});
//		}
//	}
//
//	@Override
//	@Cacheable(value = ARTICLES_CACHE_NAME, key = ARTICLES_CACHE_KEY)
//	public List<ArchiveBo> archives() {
//		// 查询文章表各个时间段的文章数量 分别为DATE->时间段 count->文章数量
//		List<ArchiveBo> listforArchiveBo = articleMapperCustom.findDateAndCount();
//		if (listforArchiveBo != null) {
//			for (ArchiveBo archiveBo : listforArchiveBo) {
//				ArticleExample example = new ArticleExample();
//				// 在EXAMPLE对象中存放article_status和article_post
//				ArticleExample.Criteria criteria = example.createCriteria().andArticleStatusEqualTo(0)
//						.andArticlePostEqualTo("post");
//				example.setOrderByClause("article_newstime desc");
//				String date = archiveBo.getDate();
//				Date sd = LocalDateTimeUtil.parse(date, "yyyy年MM月");
//				// 在criteria对象中放入article_newstime大于或者等于的值
//				criteria.andArticleNewstimeGreaterThanOrEqualTo(sd);
//				Calendar cal = Calendar.getInstance();
//				// 判断获取的时间的月份是否小于12
//				if (sd.getMonth() < 12) {
//					cal.setTime(sd);
//					// 月份 +1
//					cal.add(Calendar.MONTH, +1);
//				} else {
//					cal.setTime(sd);
//					// 年 +1
//					cal.add(Calendar.YEAR, +1);
//				}
//				SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
//				String date2 = sdf.format(cal.getTime());
//				Date date3 = LocalDateTimeUtil.parse(date2, "yyyy年MM月");
//				// 在criteria对象中放入article_newstime小于的值
//				criteria.andArticleNewstimeLessThan(date3);
//				List<Question> articles = articleMapper.selectByExample(example);
//				archiveBo.setArticles(articles);
//			}
//		}
//		return listforArchiveBo;
//	}
//
//	@Override
//	@Cacheable(value = ARTICLES_CACHE_NAME, key = "'articleUrlInt'+#articleUrl")
//	public int findRepeatByUrl(String articleUrl) {
//		return articleMapperCustom.findRepeatByUrl(articleUrl);
//	}
//
//	@Override
//	@Cacheable(value = ARTICLES_CACHE_NAME, key = "'articleUrl'+#articleUrl")
//	public Question findByArticleUrl(String articleUrl) {
//		return articleMapperCustom.findByArticleUrl(articleUrl);
//	}
//
//	@Override
//	@Cacheable(value = ARTICLES_CACHE_NAME, key = "'findArtileByCategory'+#page+#limit+#category.categoryUrl")
//	public PageInfo<Question> findArtileByCategory(int page, int limit, Category category,int status) {
//		PageHelper.startPage(page, limit);
//		List<Question> list = articleMapperCustom.findArtileByCategory(category,status);
//		return new PageInfo<>(list);
//	}
//
//	@Override
//	@Cacheable(value = ARTICLES_CACHE_NAME, key = "'findArtileByTag'+#page+#limit+#status+#tag.tagUrl")
//	public PageInfo<Question> findArtileByTag(Integer page, Integer limit, Tag tag,int status) {
//		PageHelper.startPage(page, limit);
//		List<Question> list = articleMapperCustom.findArtileByTag(tag,status);
//		return new PageInfo<>(list);
//	}
//
//	@Override
//	@Cacheable(value = ARTICLES_CACHE_NAME, key = "'findArticleByKeywords'+#keywords+#page+#limit")
//	public PageInfo<Question> findArticleByKeywords(String keywords, Integer page, Integer limit) {
//		PageHelper.startPage(page, limit);
//		ArticleExample articleExample = new ArticleExample();
//		ArticleExample.Criteria criteria = articleExample.createCriteria();
//		criteria.andArticlePostEqualTo(PostType.POST_TYPE_POST.getValue());
//		criteria.andArticleStatusEqualTo(ArticleStatus.PUBLISH.getStatus());
//		criteria.andArticleTitleLike("%" + keywords + "%");
//		articleExample.setOrderByClause("article_newstime desc");
//		List<Question> list = articleMapper.selectByExample(articleExample);
//		return new PageInfo<>(list);
//	}

}
